package com.cyx.netty.n5;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/*
Netty Hello World !
a-b-c-d-e-f-g-h-i-j-k-l-m-n
 */
public class HelloClient {
    public static void main(String[] args) throws InterruptedException {
        // 1.启动类 [f]
        new Bootstrap()
                // 2.添加EventLoop [g]
                .group(new NioEventLoopGroup())
                // 3.选择客户端channel实现 [h]
                .channel(NioSocketChannel.class)
                // 4.添加handler [i]
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override // 连接建立后被调用 [k]
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder()); // 将字符串转换成ByteBuf [m]
                    }
                })
                // 5.连接到服务器 [j]
                .connect(new InetSocketAddress("localhost", 8888))
                .sync() // 阻塞方法，直到连接建立后才会往下运行
                .channel()
                .writeAndFlush("hello world !"); // [l]
    }
}
